package com.ruoyi.dm.component.collect;


import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import com.ruoyi.common.constant.CollectFileTypeConstants;
import com.ruoyi.common.utils.biz.PathUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 数据同步定时任务类
 */
@Component
@Slf4j
public class DataCollectTask implements CommandLineRunner {

    @Autowired
    private DataCollectService dataCollectService;


    //kp采集
    @Scheduled(cron = "0 0 4 * * *")
    public  void kpCollect() {
        //查主库最新时间
        log.info("开始kp 任务结束");
        Date lastData = dataCollectService.queryTime("swdata_obs_kp", "\"DATETIME\"");
        StringBuffer sqlBuffer = new StringBuffer();
        sqlBuffer.append("select kp as index,day_hh as dataTime from ");
        sqlBuffer.append("d_gm004000 ");
        sqlBuffer.append("where day_hh > to_timestamp('");
        //世界时转北京时
        DateTime offset = DateUtil.offset(lastData, DateField.HOUR_OF_DAY, 8);
        sqlBuffer.append(DateUtil.format(offset,"yyyy-MM-dd HH:mm:ss"));
        sqlBuffer.append("','YYYY-MM-DD HH24:MI:SS')");
        log.info("kP");
        log.info(lastData.toString());
        log.info(sqlBuffer.toString());
        log.info("kP");
        List<IndexDataBO> datas = dataCollectService.queryDataGmt8(sqlBuffer.toString());
        if (null == datas || datas.size()==0) {
            log.info("kp 任务结束,无数据");
            return;
        }
        Map<Date, List<IndexDataBO>> collectByTime = datas.stream().sorted().collect(Collectors.groupingBy(one -> DateUtil.truncate(one.getDataTime(), DateField.DAY_OF_MONTH)));

        //转为文件  20230102221500_Ap.txt
        for (Map.Entry<Date, List<IndexDataBO>> dateListEntry : collectByTime.entrySet()) {
            try {
                List<IndexDataBO> boList = dateListEntry.getValue();
                Date key = boList.get(boList.size()-1).getDataTime();
                String yyyyMMddHHmmss = DateUtil.format(key, "yyyyMMddHHmmss");
                String fileName = yyyyMMddHHmmss+"_kp.txt";
                List<IndexDataBO> value = boList;
                List<String> lines = new ArrayList<>();
                //DATETIME	AP
                //1958-01-01 01:15:00	56
                lines.add("DATETIME\tKP");
                for (IndexDataBO indexDataBO : value) {

                    lines.add(DateUtil.format(indexDataBO.getDataTime(),"yyyy-MM-dd HH:mm:ss")+"\t"+indexDataBO.getIndex());
                }
                String file = PathUtil.tmpDir() + "/collect/" + fileName;
                FileUtil.writeLines(lines,file, "utf-8");
                //调用Ap的采集方法
                dataCollectService.collect(file,CollectFileTypeConstants.TYPE_EARTH,"KP");
            }catch (Exception e) {
                log.error("生成文件失败",e);
            }
        }
    }

    //Ap采集
    @Scheduled(cron = "0 10 4 * * *")
    public  void apCollect() {
        //查主库最新时间
        log.info("开始ap 任务结束");
        Date lastData = dataCollectService.queryTime("swdata_obs_ap", "\"DATETIME\"");

        StringBuffer sqlBuffer = new StringBuffer();
        sqlBuffer.append("select ap as index,day as dataTime from ");
        sqlBuffer.append("d_gm003000 ");
        sqlBuffer.append("where day > to_timestamp('");
        sqlBuffer.append(DateUtil.format(lastData,"yyyy-MM-dd HH:mm:ss"));
        sqlBuffer.append("','YYYY-MM-DD HH24:MI:SS')");
        log.info(lastData.toString());
        log.info(sqlBuffer.toString());
        List<IndexDataBO> datas = dataCollectService.queryData(sqlBuffer.toString());
        log.info("aP");
        log.info(lastData.toString());
        log.info(sqlBuffer.toString());
        log.info("aP");
        if (null == datas || datas.size()==0) {
            log.info("ap 任务结束,无数据");
            return;
        }
        Map<Date, List<IndexDataBO>> collectByTime = datas.stream().sorted().collect(Collectors.groupingBy(one -> DateUtil.truncate(one.getDataTime(), DateField.DAY_OF_MONTH)));

        //转为文件  20230102221500_Ap.txt
        for (Map.Entry<Date, List<IndexDataBO>> dateListEntry : collectByTime.entrySet()) {
            try {
                List<IndexDataBO> boList = dateListEntry.getValue();
                Date key = boList.get(boList.size()-1).getDataTime();
                String yyyyMMddHHmmss = DateUtil.format(key, "yyyyMMddHHmmss");
                String fileName = yyyyMMddHHmmss+"_Ap.txt";
                List<IndexDataBO> value = boList;
                List<String> lines = new ArrayList<>();
                //DATETIME	AP
                //1958-01-01 01:15:00	56
                lines.add("DATETIME\tAP");
                for (IndexDataBO indexDataBO : value) {
                    lines.add(DateUtil.format(indexDataBO.getDataTime(),"yyyy-MM-dd HH:mm:ss")+"\t"+indexDataBO.getIndex());
                }
                String file = PathUtil.tmpDir() + "/collect/" + fileName;
                FileUtil.writeLines(lines,file, "utf-8",false);
                //调用Ap的采集方法
                dataCollectService.collect(file,CollectFileTypeConstants.TYPE_EARTH,"AP");
            }catch (Exception e) {
                log.error("生成文件失败",e);
            }
        }
    }

    //Dst采集
    @Scheduled(cron = "0 20 4 * * *")
    public  void dstCollect() {
        //查主库最新时间
        log.info("开始dst 任务结束");
        Date lastData = dataCollectService.queryTime("swdata_obs_dst", "\"DATETIME\"");

        StringBuffer sqlBuffer = new StringBuffer();
        sqlBuffer.append("select dst_rt as index,day_hh as dataTime from ");
        sqlBuffer.append("d_gm005000 ");
        sqlBuffer.append("where day_hh > to_timestamp('");
        sqlBuffer.append(DateUtil.format(lastData,"yyyy-MM-dd HH:mm:ss"));
        sqlBuffer.append("','YYYY-MM-DD HH24:MI:SS')");
        List<IndexDataBO> datas = dataCollectService.queryData(sqlBuffer.toString());
        log.info("dst");
        log.info(lastData.toString());
        log.info(sqlBuffer.toString());
        log.info("dst");
        if (null == datas || datas.size()==0) {
            log.info("dst 任务结束,无数据");
            return;
        }
        Map<Date, List<IndexDataBO>> collectByTime = datas.stream().sorted().collect(Collectors.groupingBy(one -> DateUtil.truncate(one.getDataTime(), DateField.DAY_OF_MONTH)));

        //转为文件  20230102221500_Ap.txt
        for (Map.Entry<Date, List<IndexDataBO>> dateListEntry : collectByTime.entrySet()) {
            try {
                List<IndexDataBO> boList = dateListEntry.getValue();
                Date key = boList.get(boList.size()-1).getDataTime();
                String yyyyMMddHHmmss = DateUtil.format(key, "yyyyMMddHHmmss");
                String fileName = yyyyMMddHHmmss+"_Dst.txt";
                List<IndexDataBO> value = boList;
                List<String> lines = new ArrayList<>();
                //DATETIME	AP
                //1958-01-01 01:15:00	56
                lines.add("DATETIME\tDST");
                for (IndexDataBO indexDataBO : value) {
                    lines.add(DateUtil.format(indexDataBO.getDataTime(),"yyyy-MM-dd HH:mm:ss")+"\t"+indexDataBO.getIndex());
                }
                String file = PathUtil.tmpDir() + "/collect/" + fileName;
                FileUtil.writeLines(lines,file, "utf-8",false);
                //调用Ap的采集方法
                dataCollectService.collect(file,CollectFileTypeConstants.TYPE_EARTH,"DST");
            }catch (Exception e) {
                log.error("生成文件失败",e);
            }
        }
    }

    //f107采集
    @Scheduled(cron = "0 30 4 * * *")
    public  void f107Collect() {
        //查主库最新时间
        log.info("开始f107 任务结束");
        Date lastData = dataCollectService.queryTime("swdata_obs_f107", "\"DATETIME\"");

        StringBuffer sqlBuffer = new StringBuffer();
        sqlBuffer.append("select f107 as index,day as dataTime from ");
        sqlBuffer.append("d_sa021000 ");
        sqlBuffer.append("where day > to_timestamp('");
        sqlBuffer.append(DateUtil.format(lastData,"yyyy-MM-dd HH:mm:ss"));
        sqlBuffer.append("','YYYY-MM-DD HH24:MI:SS')");
        List<IndexDataBO> datas = dataCollectService.queryData(sqlBuffer.toString());
        log.info("f107");
        log.info(lastData.toString());
        log.info(sqlBuffer.toString());
        log.info("f107");
        if (null == datas || datas.size()==0) {
            log.info("f107 任务结束,无数据");
            return;
        }
        Map<Date, List<IndexDataBO>> collectByTime = datas.stream().sorted().collect(Collectors.groupingBy(one -> DateUtil.truncate(one.getDataTime(), DateField.DAY_OF_MONTH)));

        //转为文件  20230102221500_Ap.txt
        for (Map.Entry<Date, List<IndexDataBO>> dateListEntry : collectByTime.entrySet()) {
            try {
                List<IndexDataBO> boList = dateListEntry.getValue();
                Date key = boList.get(boList.size()-1).getDataTime();
                String yyyyMMddHHmmss = DateUtil.format(key, "yyyyMMddHHmmss");
                String fileName = yyyyMMddHHmmss+"_F107.txt";
                List<IndexDataBO> value = boList;
                List<String> lines = new ArrayList<>();
                //DATETIME	AP
                //1958-01-01 01:15:00	56
                lines.add("DATETIME\tF107");
                for (IndexDataBO indexDataBO : value) {
                    lines.add(DateUtil.format(indexDataBO.getDataTime(),"yyyy-MM-dd")+"\t"+indexDataBO.getIndex());
                }
                String file = PathUtil.tmpDir() + "/collect/" + fileName;
                FileUtil.writeLines(lines,file, "utf-8");
                //调用Ap的采集方法
                dataCollectService.collect(file,CollectFileTypeConstants.TYPE_SUN,"F107");
            }catch (Exception e) {
                log.error("生成文件失败",e);
            }
        }
    }

    //f太阳黑子
    @Scheduled(cron = "0 40 4 * * *")
    public  void snCollect() {
        //查主库最新时间
        log.info("开始sn 任务结束");
        Date lastData = dataCollectService.queryTime("swdata_obs_sn", "\"DATETIME\"");

        StringBuffer sqlBuffer = new StringBuffer();
        sqlBuffer.append("select ssn as index,day as dataTime from ");
        sqlBuffer.append("d_sa023000 ");
        sqlBuffer.append("where day > to_timestamp('");
        sqlBuffer.append(DateUtil.format(lastData,"yyyy-MM-dd HH:mm:ss"));
        sqlBuffer.append("','YYYY-MM-DD HH24:MI:SS')");
        List<IndexDataBO> datas = dataCollectService.queryData(sqlBuffer.toString());
        if (null == datas || datas.size()==0) {
            log.info("sn 任务结束,无数据");
            return;
        }
        Map<Date, List<IndexDataBO>> collectByTime = datas.stream().sorted().collect(Collectors.groupingBy(one -> DateUtil.truncate(one.getDataTime(), DateField.DAY_OF_MONTH)));

        //转为文件  20230102221500_Ap.txt
        for (Map.Entry<Date, List<IndexDataBO>> dateListEntry : collectByTime.entrySet()) {
            try {
                List<IndexDataBO> boList = dateListEntry.getValue();
                Date key = boList.get(boList.size()-1).getDataTime();
                String yyyyMMddHHmmss = DateUtil.format(key, "yyyyMMddHHmmss");
                String fileName = yyyyMMddHHmmss+"_Sn.txt";
                List<IndexDataBO> value = boList;
                List<String> lines = new ArrayList<>();
                //DATETIME	AP
                //1958-01-01 01:15:00	56
                lines.add("DATETIME\tSN");
                for (IndexDataBO indexDataBO : value) {
                    lines.add(DateUtil.format(indexDataBO.getDataTime(),"yyyy-MM-dd")+"\t"+indexDataBO.getIndex());
                }
                String file = PathUtil.tmpDir() + "/collect/" + fileName;
                FileUtil.writeLines(lines,file, "utf-8");
                //调用Ap的采集方法
                dataCollectService.collect(file,CollectFileTypeConstants.TYPE_SUN,"SN");
            }catch (Exception e) {
                log.error("生成文件失败",e);
            }
        }
    }

    @Override
    public void run(String... args) throws Exception {
        apCollect();
        kpCollect();
        dstCollect();
        f107Collect();
        snCollect();
    }
}
